
#include "win_file_mgr.hpp"

#include <Windows.h>

class WinFile : public File
{
public:
	WinFile( HANDLE handle ) : handle_( handle ) {}
	int size() {
		return GetFileSize( handle_, NULL );
	}
	int read( char * buffer, int size ) {
		DWORD readed = 0;
		if ( ReadFile( handle_, buffer, DWORD(size), &readed, NULL ) ) {
			return (int)readed;
		}
		return 0;
	}
	void close() {
		if ( handle_ ){
			CloseHandle( handle_ );
			handle_ = 0;
		}
	}
	void seek( int pos ) {
		SetFilePointer( handle_, pos, NULL, FILE_BEGIN );
	}
private:
	HANDLE handle_;
};

FilePtr WinFileMgr::open(const std::string &name)
{
	std::string path = root_ + name;
	HANDLE handle = ::CreateFile( path.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, \
		OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );
	
	if ( handle == INVALID_HANDLE_VALUE ) {
		return FilePtr();
	}
	
	return new WinFile( handle );
}

BinaryPtr WinFileMgr::read( const std::string & name )
{
	FilePtr file = open( name );
	if ( !file ) {
		return BinaryPtr();
	}
	BinaryPtr bin = new Binary( file->size() );
	file->read( bin->data(), bin->size() );
	return bin;
}



